package edu.washington.ling.syntric.consistency;

import java.util.LinkedList;
import java.util.List;

import edu.washington.ling.syntric.struct.tree.Token;
import edu.washington.ling.syntric.struct.tree.Tree;
import edu.washington.ling.syntric.util.Pair;
import edu.washington.ling.syntric.util.TreeUtils;

public class OrderUtils {
	public static boolean isSuitableAnchor(Token t) {
		return (!t.isScrambledLongDistance() && !t.isScrambledOverArgument() && !t.isExtraposed());
	}
	public static List<Token> getInnerSiblings(Token dep, Token head, Tree ds, String direction) {
		List<Token> innerSiblings = new LinkedList<Token>();
		if (direction.equals("left")) {
			innerSiblings = TreeUtils.getLeftInnerDSSiblings(dep, head, ds);
			TreeUtils.sortTokens(innerSiblings, ds);
		} else {
			innerSiblings = TreeUtils.getRightInnerDSSiblings(dep, head, ds);
			TreeUtils.sortTokens(innerSiblings, ds, true);
		}
		return innerSiblings;
	}
	
	public static void attachAdjacentToHeadSpan(Token t, Token head, Tree ds, String direction) {
		if (direction.equals("left")) {
			insertLeftOfSpan(t, head, ds);
		} else {
			insertRightOfSpan(t, head, ds);
		}
		head.addDSDependent(t);
		t.setDSHead(head);
	}
	public static void attachAdjacentToHeadToken(Token t, Token head, Tree ds, String direction) {
		if (direction.equals("left")) {
			insertLeftOfToken(t, head, ds);
		} else {
			insertRightOfToken(t, head, ds);
		}
		head.addDSDependent(t);
		t.setDSHead(head);
	}
	
	public static void attachAdjacentToSiblingSpan(Token t, Token sibling, Token head, Tree ds, String direction) {
		if (direction.equals("left")) {
			insertLeftOfSpan(t, sibling, ds);
		} else {
			insertRightOfSpan(t, sibling, ds);
		}
		head.addDSDependent(t);
		t.setDSHead(head);
	}
	public static void insertLeftOfSpan(Token t, Token target, Tree ds) {
		Pair<Integer, Integer> targetSpan = TreeUtils.getSpan(target, ds);
		ds.insertTokenLeft(targetSpan.getLeft(), t);
	}
	public static void insertRightOfSpan(Token t, Token target, Tree ds) {
		Pair<Integer, Integer> targetSpan = TreeUtils.getSpan(target, ds);
		ds.insertTokenRight(targetSpan.getRight(), t);
	}
	public static void insertLeftOfToken(Token t, Token target, Tree ds) {
		int targetPos = ds.getTokenPosition(target);
		ds.insertTokenLeft(targetPos, t);
	}
	public static void insertRightOfToken(Token t, Token target, Tree ds) {
		int targetPos = ds.getTokenPosition(target);
		ds.insertTokenRight(targetPos, t);
	}
}
